<template>
  <div class="report-container">
    <div class="page-header">
      <h2>销售数据报表</h2>
      <el-button type="primary" icon="el-icon-refresh" @click="fetchData">刷新数据</el-button>
    </div>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>站点销售数据</span>
            <div class="chart-actions">
              <el-radio-group v-model="stationChartType" size="small">
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="pie">饼图</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-container">
            <div ref="stationChart" class="chart"></div>
          </div>
          <div class="chart-summary">
            <div class="summary-item">
              <div class="summary-label">总订单数</div>
              <div class="summary-value">{{ stationTotalOrders }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">总销售额</div>
              <div class="summary-value">¥{{ formatPrice(stationTotalPrice) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>回收类型销售数据</span>
            <div class="chart-actions">
              <el-radio-group v-model="typeChartType" size="small">
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="pie">饼图</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-container">
            <div ref="typeChart" class="chart"></div>
          </div>
          <div class="chart-summary">
            <div class="summary-item">
              <div class="summary-label">总订单数</div>
              <div class="summary-value">{{ typeTotalOrders }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">总销售额</div>
              <div class="summary-value">¥{{ formatPrice(typeTotalPrice) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'SalesReport',
  data() {
    return {
      stationData: [],
      typeData: [],
      stationChart: null,
      typeChart: null,
      stationChartType: 'bar',
      typeChartType: 'bar',
      stationTotalOrders: 0,
      stationTotalPrice: 0,
      typeTotalOrders: 0,
      typeTotalPrice: 0
    }
  },
  mounted() {
    this.initCharts()
    this.fetchData()
  },
  methods: {
    async fetchData() {
      try {
        // 获取类型数据
        const typeRes = await this.$http.get('/recycle/recyclingOrder/selectAllOrderByType')
        if (typeRes.data.code === 200) {
          console.log('接收到的原始数据:', typeRes.data.data)
          
          // 确保数据格式正确
          this.typeData = typeRes.data.data.map(item => ({
            type: item.type || '未知类型',
            orders: Number(item.orders) || 0,
            totalPrice: Number(item.totalPrice) || 0
          }))
          
          console.log('处理后的数据:', this.typeData)
          
          this.calculateTypeTotals()
          
          // 确保DOM已经渲染
          await this.$nextTick()
          
          // 如果图表实例不存在，重新初始化
          if (!this.typeChart && this.$refs.typeChart) {
            console.log('初始化图表实例')
            this.typeChart = echarts.init(this.$refs.typeChart)
          }
          
          this.updateTypeChart()
        }

        // 获取站点数据
        const stationRes = await this.$http.get('/recycle/recyclingOrder/selectAllOrderByStation')
        if (stationRes.data.code === 200) {
          this.stationData = stationRes.data.data
          this.calculateStationTotals()
          this.$nextTick(() => {
            this.updateStationChart()
          })
        }
      } catch (error) {
        console.error('获取数据失败：', error)
        this.$message.error('获取数据失败')
      }
    },

    initCharts() {
      // 确保DOM已经渲染完成
      this.$nextTick(() => {
        try {
          // 初始化站点图表
          if (this.$refs.stationChart) {
            this.stationChart = echarts.init(this.$refs.stationChart)
            console.log('站点图表初始化成功')
          }
          // 初始化类型图表
          if (this.$refs.typeChart) {
            this.typeChart = echarts.init(this.$refs.typeChart)
            console.log('类型图表初始化成功')
          }

          // 监听窗口大小变化
          window.addEventListener('resize', this.handleResize)
        } catch (error) {
          console.error('图表初始化失败：', error)
        }
      })
    },

    handleResize() {
      if (this.stationChart) {
        this.stationChart.resize()
      }
      if (this.typeChart) {
        this.typeChart.resize()
      }
    },

    calculateStationTotals() {
      this.stationTotalOrders = this.stationData.reduce((sum, item) => sum + item.orders, 0)
      this.stationTotalPrice = this.stationData.reduce((sum, item) => sum + item.totalPrice, 0)
    },

    calculateTypeTotals() {
      this.typeTotalOrders = this.typeData.reduce((sum, item) => sum + item.orders, 0)
      this.typeTotalPrice = this.typeData.reduce((sum, item) => sum + parseFloat(item.totalPrice), 0)
    },

    updateStationChart() {
      if (!this.stationChart || !this.stationData.length) return

      try {
        let option = {
          title: {
            text: '站点销售数据统计',
            left: 'center',
            top: 10
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              let result = params[0].name + '<br/>'
              params.forEach(param => {
                let value = param.seriesName === '销售额' 
                  ? '¥' + Number(param.value).toLocaleString()
                  : param.value
                result += param.seriesName + ': ' + value + '<br/>'
              })
              return result
            }
          },
          legend: {
            data: ['订单数', '销售额'],
            top: 40
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
            top: 100
          },
          xAxis: {
            type: 'category',
            data: this.stationData.map(item => item.stationName),
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '订单数',
              position: 'left',
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#409EFF'
                }
              },
              splitLine: {
                show: false
              }
            },
            {
              type: 'value',
              name: '销售额',
              position: 'right',
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#67C23A'
                }
              },
              splitLine: {
                show: false
              }
            }
          ],
          series: [
            {
              name: '订单数',
              type: 'bar',
              data: this.stationData.map(item => item.orders),
              itemStyle: {
                color: '#409EFF'
              },
              barWidth: '20%'
            },
            {
              name: '销售额',
              type: 'bar',
              yAxisIndex: 1,
              data: this.stationData.map(item => Number(item.totalPrice)),
              itemStyle: {
                color: '#67C23A'
              },
              barWidth: '20%'
            }
          ]
        }

        this.stationChart.setOption(option, true)
      } catch (error) {
        console.error('更新站点图表时出错：', error)
      }
    },

    updateTypeChart() {
      if (!this.typeChart || !this.typeData.length) {
        console.log('图表实例或数据不存在')
        return
      }

      console.log('准备更新图表，数据：', this.typeData)

      try {
        const option = {
          title: {
            text: '各类型销售额统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: function(params) {
              return `${params[0].name}<br/>销售额: ¥${params[0].value.toLocaleString()}`
            }
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '10%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.typeData.map(item => item.type || '未知类型'),
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: {
            type: 'value',
            name: '销售额（元）',
            axisLabel: {
              formatter: (value) => '¥' + value.toLocaleString()
            }
          },
          series: [{
            name: '销售额',
            type: 'bar',
            barWidth: '40%',
            data: this.typeData.map(item => ({
              value: Number(item.totalPrice),
              itemStyle: {
                color: '#409EFF'
              }
            })),
            label: {
              show: true,
              position: 'top',
              formatter: '¥{c}'
            }
          }]
        }

        console.log('设置图表配置')
        this.typeChart.setOption(option, true)
        console.log('图表配置已设置')
      } catch (error) {
        console.error('更新图表时出错：', error)
      }
    },

    formatPrice(price) {
      return price.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }
  },
  watch: {
    stationChartType() {
      this.updateStationChart()
    },
    typeChartType() {
      this.updateTypeChart()
    }
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.stationChart) {
      this.stationChart.dispose()
    }
    if (this.typeChart) {
      this.typeChart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>

<style scoped>
.report-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

.chart-card {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-container {
  position: relative;
  height: 400px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
  margin: 10px 0;
}

.chart {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-summary {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background: #fafafa;
  border-radius: 0 0 8px 8px;
}

.summary-item {
  text-align: center;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

.chart-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .chart-container {
    height: 300px;
  }

  .summary-value {
    font-size: 20px;
  }
}
</style> 